/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RemoteDesktop;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;

/**
 *
 * @author Oho
 */
public class ThreadImages extends Thread {

    Socket sk;
    Robot rb;
    Rectangle rt;

    ThreadImages(Socket sk, Robot robot, Rectangle rectangle) {
        this.sk = sk;
        this.rb = robot;
        this.rt = rectangle;
    }

    @Override
    public void run() {
        try {
            ObjectOutputStream oos = null;
            oos = new ObjectOutputStream(sk.getOutputStream());
            oos.writeObject(rt);
            while (true) {
                //Capture screen
                BufferedImage image = rb.createScreenCapture(rt);
                /* I have to wrap BufferedImage with ImageIcon because BufferedImage class
                 * does not implement Serializable interface
                 */
                ImageIcon imageIcon = new ImageIcon(image);

                //Send captured screen to the server
                try {
                    System.out.println("before sending image");
                    oos.writeObject(imageIcon);
                    oos.reset(); //Clear ObjectOutputStream cache
                    System.out.println("New screenshot sent");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

                //wait for 100ms to reduce network traffic
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        } catch (IOException ex) {
            Logger.getLogger(ThreadImages.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
